using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using FireStarter.CodeGeneration.Generator;

namespace FireStarter.CodeGeneration.Parser
{
    public class IncludeExpressionParser : ActionParserBase
    {
        private static readonly Regex _regex = new Regex(@"\AINCLUDE[(]!*.*\w*[)]");

        public IncludeExpressionParser(ITemplateLoader templateLoader) : base(templateLoader) {
            
        }

        public override TemplateExpression Parse(ref string templateText, List<IActionParser> actionParsers)
        {
            int openBracketPos = templateText.IndexOf("(");
            int closeBracketPos = templateText.IndexOf(")");
            openBracketPos++;
            string includeName = templateText.Substring(openBracketPos, closeBracketPos - openBracketPos);
            StatementParser statementParser = new StatementParser();
            string includeText = TemplateLoader.GetTemplateText(includeName);
            TemplateExpression part = statementParser.Parse(ref includeText, actionParsers);
            string statementText = templateText.Substring(closeBracketPos + 1);
            TemplateExpression next = statementParser.Parse(ref statementText, actionParsers);
            templateText = "";
            return new IncludeExpression(part, next);
        }

        public override bool IsExpressionMatch(string text) { return text != null && _regex.IsMatch(text); }
    }
}